import React, { useEffect, useState } from 'react'
import { SideBar, Tabs, Toast, NavBar } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import request from '../../api/request'
import './index.css'

interface DepartmentItem {
  id?: string
  departmentId?: string
  departmentName: string
}

interface DiseaseItem {
  id: number
  departmentId: number
  name: string
}

interface DrugCategoryItem {
  id: number
  name: string
  rank: number
}

interface DrugItem {
  id: number
  drugsCategoryId: number
  name: string
  picture: string
  mockImage?: string
}

interface DrugApiResponse {
  id: number
  drugsCategoryId: number
  name: string
  picture: string
}

function Index() {
  const navigate = useNavigate()
  const [data, setData] = useState<DepartmentItem[]>([])
  const [drugCategories, setDrugCategories] = useState<DrugCategoryItem[]>([])
  const [activeKey, setActiveKey] = useState<string>('')
  const [activeDrugCategoryKey, setActiveDrugCategoryKey] = useState<string>('')
  const [diseaseData, setDiseaseData] = useState<DiseaseItem[]>([])
  const [drugData, setDrugData] = useState<DrugItem[]>([])
  const [activeTab, setActiveTab] = useState<string>('disease')
  const [loading, setLoading] = useState<boolean>(false)
  const [diseaseLoading, setDiseaseLoading] = useState<boolean>(false)
  const [drugLoading, setDrugLoading] = useState<boolean>(false)

  // 返回上一页
  const handleBack = () => {
    navigate(-1)
  }

  // 跳转到疾病详情页
  const handleDiseaseClick = (disease: DiseaseItem) => {
    navigate(`/disease-detail/${disease.id}`, {
      state: { disease }
    })
  }

  // 跳转到药品详情页
  const handleDrugClick = (drug: DrugItem) => {
    navigate(`/drug-detail/${drug.id}`, {
      state: { drug }
    })
  }

  const getdata = () => {
    setLoading(true)
    request.get('/health/share/knowledgeBase/v1/findDepartment').then((res) => {
      console.log(res);
      if (res.status === 200) {
        setData(res.data.result)
        // 设置默认选中的第一个分类
        if (res.data.result.length > 0) {
          const firstItem = res.data.result[0]
          const key = firstItem.id || firstItem.departmentId || firstItem.departmentName
          setActiveKey(key)
          // 获取第一个分类的疾病数据
          getDiseaseData(key)
        }
      } else {
        Toast.show({
          content: '获取数据失败',
          position: 'center',
        })
      }
    }).catch((error) => {
      console.error('获取部门数据失败:', error)
      Toast.show({
        content: '网络错误，请重试',
        position: 'center',
      })
    }).finally(() => {
      setLoading(false)
    })
  }

  const getDrugCategories = () => {
    setDrugLoading(true)
    request.get('/health/share/knowledgeBase/v1/findDrugsCategoryList').then((res) => {
      console.log('药品类目数据:', res);
      if (res.status === 200 && res.data.status === '0000') {
        setDrugCategories(res.data.result || [])
        // 设置默认选中的第一个药品类目
        if (res.data.result.length > 0) {
          const firstCategory = res.data.result[0]
          setActiveDrugCategoryKey(firstCategory.id.toString())
          // 获取第一个类目的药品数据
          getDrugData(firstCategory.id, 1, 10)
        }
      } else {
        Toast.show({
          content: res.data.message || '获取药品类目失败',
          position: 'center',
        })
        setDrugCategories([])
      }
    }).catch((error) => {
      console.error('获取药品类目失败:', error)
      Toast.show({
        content: '获取药品类目失败，请重试',
        position: 'center',
      })
      setDrugCategories([])
    }).finally(() => {
      setDrugLoading(false)
    })
  }

  const getDiseaseData = (departmentId: string) => {
    setDiseaseLoading(true)
    // 调用真实的API接口获取疾病数据
    request.get('/health/share/knowledgeBase/v1/findDiseaseCategory', {
      params: {
        departmentId: departmentId
      }
    }).then((res) => {
      console.log('疾病数据:', res);
      if (res.status === 200 && res.data.status === '0000') {
        setDiseaseData(res.data.result || [])
      } else {
        Toast.show({
          content: res.data.message || '获取疾病数据失败',
          position: 'center',
        })
        setDiseaseData([])
      }
    }).catch((error) => {
      console.error('获取疾病数据失败:', error)
      Toast.show({
        content: '获取疾病数据失败，请重试',
        position: 'center',
      })
      setDiseaseData([])
    }).finally(() => {
      setDiseaseLoading(false)
    })
  }

  const getDrugData = (categoryId: number, page: number = 1, count: number = 10) => {
    setDrugLoading(true)
    request.get('/health/share/knowledgeBase/v1/findDrugsKnowledgeList', {
      params: {
        drugsCategoryId: categoryId,
        page: page,
        count: count
      }
    }).then((res) => {
      console.log('药品数据:', res);
      if (res.status === 200 && res.data.status === '0000') {
        // 为每个药品添加模拟图片
        const drugsWithImages = (res.data.result || []).map((drug: DrugApiResponse, index: number) => ({
          ...drug,
          mockImage: getMockDrugImage(drug.name, index)
        }))
        setDrugData(drugsWithImages)
      } else {
        Toast.show({
          content: res.data.message || '获取药品数据失败',
          position: 'center',
        })
        setDrugData([])
      }
    }).catch((error) => {
      console.error('获取药品数据失败:', error)
      Toast.show({
        content: '获取药品数据失败，请重试',
        position: 'center',
      })
      setDrugData([])
    }).finally(() => {
      setDrugLoading(false)
    })
  }

  // 根据药品名称和索引生成模拟图片
  const getMockDrugImage = (drugName: string, index: number): string => {
    const mockImages = [
      'https://img.freepik.com/free-photo/medicine-capsules-global-health-with-geometric-pattern-digital-remix_53876-126742.jpg',
      'https://img.freepik.com/free-photo/pills-capsules-medicine-healthcare-concept_53876-124422.jpg',
      'https://img.freepik.com/free-photo/medicine-capsules-global-health-with-geometric-pattern-digital-remix_53876-126743.jpg',
      'https://img.freepik.com/free-photo/pills-capsules-medicine-healthcare-concept_53876-124423.jpg',
      'https://img.freepik.com/free-photo/medicine-capsules-global-health-with-geometric-pattern-digital-remix_53876-126744.jpg',
      'https://img.freepik.com/free-photo/pills-capsules-medicine-healthcare-concept_53876-124424.jpg',
      'https://img.freepik.com/free-photo/medicine-capsules-global-health-with-geometric-pattern-digital-remix_53876-126745.jpg',
      'https://img.freepik.com/free-photo/pills-capsules-medicine-healthcare-concept_53876-124425.jpg'
    ]
    
    // 根据药品名称或索引选择图片
    if (drugName.includes('感冒') || drugName.includes('退烧')) {
      return 'https://img.freepik.com/free-photo/medicine-capsules-global-health-with-geometric-pattern-digital-remix_53876-126742.jpg'
    } else if (drugName.includes('消炎') || drugName.includes('抗生素')) {
      return 'https://img.freepik.com/free-photo/pills-capsules-medicine-healthcare-concept_53876-124422.jpg'
    } else if (drugName.includes('维生素') || drugName.includes('钙片')) {
      return 'https://img.freepik.com/free-photo/medicine-capsules-global-health-with-geometric-pattern-digital-remix_53876-126743.jpg'
    } else {
      // 根据索引循环使用图片
      return mockImages[index % mockImages.length]
    }
  }

  const handleSideBarChange = (value: string) => {
    if (activeTab === 'disease') {
      setActiveKey(value)
      getDiseaseData(value)
    } else {
      setActiveDrugCategoryKey(value)
      getDrugData(parseInt(value), 1, 10)
    }
  }

  const handleTabChange = (key: string) => {
    setActiveTab(key)
    if (key === 'medicine') {
      // 切换到药品标签页，获取药品类目数据
      getDrugCategories()
    } else {
      // 切换到疾病标签页，重新获取疾病数据
      if (activeKey) {
        getDiseaseData(activeKey)
      }
    }
  }

  useEffect(() => {
    getdata()
  }, [])

  if (loading && data.length === 0) {
    return (
      <div className="loading-container">
        <div className="loading-text">加载中...</div>
      </div>
    )
  }

  return (
    <div className="fen-container">
      {/* 头部导航栏 */}
      <div className="header-navbar">
        <NavBar onBack={handleBack} className="custom-navbar">
          健康知识库
        </NavBar>
      </div>

      {/* 顶部标签页 */}
      <div className="tabs-container">
        <Tabs
          activeKey={activeTab}
          onChange={handleTabChange}
          className="custom-tabs"
        >
          <Tabs.Tab title="常见病症" key="disease" />
          <Tabs.Tab title="常用药品" key="medicine" />
        </Tabs>
      </div>

      {/* 主要内容区域 */}
      <div className="main-content">
        {/* 左侧侧边导航 */}
        <div className="sidebar-container">
          <SideBar 
            activeKey={activeTab === 'disease' ? activeKey : activeDrugCategoryKey} 
            onChange={handleSideBarChange}
          >
            {activeTab === 'disease' ? (
              // 疾病科室导航
              data.map((item, index) => (
                <SideBar.Item 
                  key={item.id || item.departmentId || item.departmentName || index} 
                  title={item.departmentName} 
                />
              ))
            ) : (
              // 药品类目导航
              drugCategories.map((category) => (
                <SideBar.Item 
                  key={category.id.toString()} 
                  title={category.name} 
                />
              ))
            )}
          </SideBar>
        </div>

        {/* 右侧内容区域 */}
        <div className="content-container">
          <div className="content-header">
            <h3 className="content-title">
              {activeTab === 'disease' ? '常见病症' : '常用药品'}
            </h3>
          </div>
          
          {activeTab === 'disease' ? (
            // 疾病内容
            diseaseLoading ? (
              <div className="loading-container">
                <div className="loading-text">加载疾病数据中...</div>
              </div>
            ) : diseaseData.length > 0 ? (
              <div className="disease-grid">
                {diseaseData.map((disease) => (
                  <div key={disease.id} className="disease-item" onClick={() => handleDiseaseClick(disease)}>
                    {disease.name}
                  </div>
                ))}
              </div>
            ) : (
              <div className="empty-container">
                <div className="empty-text">暂无疾病数据</div>
              </div>
            )
          ) : (
            // 药品内容
            drugLoading ? (
              <div className="loading-container">
                <div className="loading-text">加载药品数据中...</div>
              </div>
            ) : drugData.length > 0 ? (
              <div className="drug-grid">
                {drugData.map((drug) => (
                  <div key={drug.id} className="drug-item" onClick={() => handleDrugClick(drug)}>
                    <div className="drug-image">
                      <img 
                        src={drug.mockImage || drug.picture || 'https://img.freepik.com/free-photo/medicine-capsules-global-health-with-geometric-pattern-digital-remix_53876-126742.jpg'} 
                        alt={drug.name}
                        onError={(e) => {
                          // 图片加载失败时使用默认图片
                          const target = e.target as HTMLImageElement
                          target.src = 'https://img.freepik.com/free-photo/medicine-capsules-global-health-with-geometric-pattern-digital-remix_53876-126742.jpg'
                        }}
                      />
                    </div>
                    <div className="drug-name">{drug.name}</div>
                  </div>
                ))}
              </div>
            ) : (
              <div className="empty-container">
                <div className="empty-text">暂无药品数据</div>
              </div>
            )
          )}
        </div>
      </div>
    </div>
  )
}

export default Index
